package com.boguan.web.controller.device;

import com.alibaba.fastjson.JSONObject;
import com.boguan.common.annotation.Log;
import com.boguan.common.annotation.RepeatSubmit;
import com.boguan.common.constant.UserConstants;
import com.boguan.common.core.controller.BaseController;
import com.boguan.common.core.domain.AjaxResult;
import com.boguan.common.core.domain.entity.SysUser;
import com.boguan.common.core.domain.model.LoginUser;
import com.boguan.common.core.page.TableDataInfo;
import com.boguan.common.utils.SecurityUtils;
import com.boguan.common.utils.StringUtils;
import com.boguan.device.domain.*;
import com.boguan.device.domain.dto.*;
import com.boguan.device.domain.vo.DeviceListVo;
import com.boguan.device.mapper.DeviceAlarmLogMapper;
import com.boguan.device.mapper.DeviceLogMapper;
import com.boguan.device.mapper.DeviceMapper;
import com.boguan.device.service.IDeviceAlarmService;
import com.boguan.device.service.IDeviceService;
import com.boguan.device.service.IDeviceTypeService;
import com.boguan.system.service.ISysConfigService;
import com.boguan.web.controller.mqtt.MqttPushClient;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("device")
@Api(tags = "设备相关")
public class DeviceController extends BaseController {

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    DeviceMapper deviceMapper;
    @Autowired
    DeviceLogMapper deviceLogMapper;



    @ApiOperation("设备详情")
    @GetMapping("deviceDetail/{id}")
    public AjaxResult deviceDetail(@PathVariable @RequestBody String id){
        return AjaxResult.success(deviceService.deviceDetail(id));
    }


    @ApiOperation("设备列表")
    @GetMapping("devicelist")
    public AjaxResult devicelist(Long deptId){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(loginUser.getUser().isAdmin()){
            return AjaxResult.success(deviceService.getAllDeviceList(null));
        }

        return  AjaxResult.success(deviceService.getAllDeviceList(deptId));


    }
    @ApiOperation("设备搜索")
    @PostMapping("/deviceSearch")
    public AjaxResult deviceSearch(DeviceSearchDto dto){

        return AjaxResult.success(deviceService.searchDeviceName(dto));

    }

    @Log(title = "设备创建")
    @ApiOperation("设备添加")
    @PostMapping("deviceAdd")
    @RepeatSubmit
    public AjaxResult deviceAdd(@RequestBody @ApiParam("设备信息参数") DeviceInfoDto dto){

        List<DeviceListVo> deviceListVos = deviceService.checkDeviceNum(dto.getDeviceNo());
        if(deviceListVos.size()!=0){
           return  AjaxResult.error("设备号已存在");
        }

        if(deviceService.insertDevice(dto)>0){
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");

    }

    @ApiOperation("设备删除")
    @PostMapping("deviceDelete")
    public AjaxResult deviceDelete(String device_id){

        deviceService.deviceDelete(device_id);
        return AjaxResult.success("删除成功");

    }
    @ApiOperation("修改设备名称")
    @PostMapping("deviceModify")
    public AjaxResult deviceModify(Long deviceId,String deviceName,String deviceNo,String locations,String height,String low){
        deviceService.deviceModify(deviceId, deviceName,deviceNo,locations,height,low);
        return AjaxResult.success();
    }

    @ApiOperation("设备分组列表")
    @GetMapping("deviceGroup")
    public AjaxResult deviceGroup(){
        return AjaxResult.success(deviceService.deviceGroup(null,null));
    }

    @ApiOperation("设备分组详情")
    @GetMapping("deviceGroupDetail")
    public AjaxResult deviceGroupDetail(Integer groupId){
        return AjaxResult.success(deviceService.deviceGroupDetail(groupId));
    }

    @ApiOperation("设备详情报警历史数据")
    @PostMapping("deviceDetailAlarmHistory")
    public AjaxResult deviceDetailAlarmHistory(@RequestBody AlarmHistoryDto dto){
        return AjaxResult.success(deviceService.deviceDetailAlarmHistory(dto));
    }

    @ApiOperation("设备分组修改")
    @PostMapping("deviceGroupEdit")
    public AjaxResult deviceGroupEdit(@ApiParam("分组名称")@RequestParam("group_name") String group_name,@ApiParam("分组id") @RequestParam("id")String id){
        if(deviceService.deviceGroupEdit(group_name,id)>0){
            return AjaxResult.success();
        }
        return AjaxResult.error();

    }

    @ApiOperation("创建设备分组")
    @PostMapping("createDeviceGroup")
    public AjaxResult createDeviceGroup(@ApiParam("分组名称")@RequestParam("name") String name){
        AddGroupDto addGroupDto = new AddGroupDto();
        addGroupDto.setName(name);
        if(deviceService.createDeviceGroup(addGroupDto)>0){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @ApiOperation("添加设备到分组")
    @PostMapping("addToDeviceGroup")
    public AjaxResult addToDeviceGroup(@ApiParam("设备ids") @RequestBody List<String> ids,String groupName){
        deviceService.addToDeviceGroup(ids, groupName);
        return AjaxResult.success();
    }

    @ApiOperation("删除分组")
    @PostMapping("deleteDeviceGroup")
    public AjaxResult deleteDeviceGroup(String group_id){
        deviceService.deleteDeviceGroup(group_id);
        return AjaxResult.success();
    }

    @ApiOperation("从分组中删除设备")
    @PostMapping("deleteDeviceFromGroup")
    public AjaxResult deleteDeviceFromGroup(String device_id){
        deviceService.deleteDeviceFromGroup(device_id);
        return AjaxResult.success();

    }

    @ApiOperation("搜索设备分组")
    @PostMapping("/deviceGroupSearch")
    public AjaxResult deviceGroupSearch(String id ,String group_name){
        return AjaxResult.success(deviceService.deviceGroup(id, group_name));
    }

    @ApiOperation("已有分组添加设备")
    @PostMapping("deviceToGroup")
    public AjaxResult deviceToGroup(String group_id,String device_id){

        return AjaxResult.success(deviceService.deviceToGroup(group_id, device_id));
    }

//    @ApiOperation("测试")
//    @GetMapping("/createDevice/{deviceName}")
//    public AjaxResult createDevice(@PathVariable String deviceName){
//        deviceService.createDevice(deviceName);
//        return AjaxResult.success();
//    }


    @PostMapping("/device/status")
    public void deviceStatus(@RequestHeader String token, @RequestBody JSONObject jsonObject){

        if ("power".equals(token)) {
            logger.info("接收消息:{}", jsonObject.toJSONString());
            Device device = deviceMapper.selectByDeviceNum(jsonObject.getString("clientid"),1);
            if (StringUtils.isNull(device)) {
                return;
            }
            if (jsonObject.getString("event").contains("disconnected")) {
                DeviceLog deviceLog = new DeviceLog();
                deviceLog.setDeviceId(device.getDeviceId());
                deviceLog.setContent("设备下线");
                deviceLog.setLogTime(new Date());
                deviceLog.setType(2);
                deviceLogMapper.insertSelective(deviceLog);
                logger.info("设备：{},下线", jsonObject.getString("clientid"));
                device.setOnlineStatus(2);


            } else if (jsonObject.getString("event").contains("connected")) {
                DeviceLog deviceLog = new DeviceLog();
                deviceLog.setDeviceId(device.getDeviceId());
                deviceLog.setContent("设备上线");
                deviceLog.setLogTime(new Date());
                deviceLog.setType(1);
                deviceLogMapper.insertSelective(deviceLog);
                logger.info("设备：{},上线", jsonObject.getString("clientid"));
                device.setOnlineStatus(1);

            }

            deviceMapper.updateByPrimaryKeySelective(device);
        }

    }











}
